package com.ls.lserp.modules.job.service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.dbaccess.Dao.ContractAdvanceEntityMapper;
import com.ls.lserp.dbaccess.Dao.ContractCustomEntityMapper;
import com.ls.lserp.dbaccess.Dao.ContractEntityMapper;
import com.ls.lserp.dbaccess.Dao.ContractMeterialEntityMapper;
import com.ls.lserp.dbaccess.Dao.ContractProcessingEntityMapper;
import com.ls.lserp.dbaccess.Dao.FinanceEntityMapper;
import com.ls.lserp.dbaccess.Dao.SampleEntityMapper;
import com.ls.lserp.dbaccess.Entity.ContractAdvanceEntity;
import com.ls.lserp.dbaccess.Entity.ContractCustomEntity;
import com.ls.lserp.dbaccess.Entity.ContractEntity;
import com.ls.lserp.dbaccess.Entity.ContractMeterialEntity;
import com.ls.lserp.dbaccess.Entity.ContractProcessingEntity;
import com.ls.lserp.dbaccess.Entity.FinanceEntity;
import com.ls.lserp.dbaccess.Entity.OgnizationSettlementEntity;
import com.ls.lserp.dbaccess.Entity.SampleEntity;
import com.ls.lserp.modules.finance.dao.InitFinanceDao;
import com.ls.lserp.modules.setting.dao.OgnizationDao;
import com.ls.lserp.modules.setting.entity.Ognization;


/** 
 * @ClassName	: FinanceSyncService 
 * @Description	: 抽取采购合同、外发合同、预付款、样品和大货定制合同中已审核通过的数据存入业务结算表，且更新以上表状态。
 * @author		: shaoyun.tan
 * @date		: 2017年11月20日 
 */
@Service
@Transactional(readOnly = false)
public class FinanceSyncService {
	
	@Autowired
	private ContractMeterialEntityMapper contractMeterialEntityMapper;//采购合同 c_contract_meterial_p
	
	@Autowired
	private ContractProcessingEntityMapper contractProcessingEntityMapper;//外发加工合同c_contract_processing_p
	
	@Autowired
	private ContractAdvanceEntityMapper contractAdvanceEntityMapper;//采购预付款 c_contract_advance_p
	
	@Autowired
	private SampleEntityMapper sampleEntityMapper;//样品需求 s_sample_p
	
	@Autowired
	private ContractEntityMapper contractEntityMapper;//大货合同 c_contract_p

	@Autowired
	private ContractCustomEntityMapper contractCustomEntityMapper;//定制合同 c_contract_custom_p
	
	@Autowired
	private FinanceEntityMapper financeEntityMapper;//财务业务管理
	
	@Autowired
    private InitFinanceDao initFinanceDao;//初期财务管理
	
	@Autowired
	private OgnizationDao ognizationDao;
	
	/** 
	 * @Title       : findContractMeterialList 
	 * @Description : 取得采购合同数据
	 * @throws  	: Exception
	 * @return      : List<ContractMeterialEntity>
	 * @author      : shaoyun.tan
	 * @date        : 2017年11月20日
	 */
	public List<ContractMeterialEntity> findContractMeterialListForFinance(ContractMeterialEntity contractMeterialEntity) throws Exception {
		return contractMeterialEntityMapper.findListForFinance(contractMeterialEntity);
	}
	
	/** 
	 * @Title       : findContractProcessingList 
	 * @Description : 取得外发加工合同数据
	 * @throws  	: Exception
	 * @return      : List<ContractProcessingEntity>
	 * @author      : shaoyun.tan
	 * @date        : 2017年11月20日
	 */
	public List<ContractProcessingEntity> findContractProcessingListForFinance(ContractProcessingEntity contractProcessingEntity) throws Exception {
		return contractProcessingEntityMapper.findListForFinance(contractProcessingEntity);
	}
	
	/** 
	 * @Title       : findContractAdvanceList 
	 * @Description : 取得采购预付款数据
	 * @throws  	: Exception
	 * @return      : List<ContractAdvanceEntity>
	 * @author      : shaoyun.tan
	 * @date        : 2017年11月20日
	 */
	public List<ContractAdvanceEntity> findContractAdvanceListForFinance(ContractAdvanceEntity contractAdvanceEntity) throws Exception {
		return contractAdvanceEntityMapper.findListForFinance(contractAdvanceEntity);
	}
	
	/** 
	 * @Title       : findSampleList 
	 * @Description : 取得样品需求数据
	 * @throws  	: Exception
	 * @return      : List<SampleEntity>
	 * @author      : shaoyun.tan
	 * @date        : 2017年11月20日
	 */
	public List<SampleEntity> findSampleListForFinance(SampleEntity sampleEntity) throws Exception {
		return sampleEntityMapper.findListForFinance(sampleEntity);
	}
	
	/** 
	 * @Title       : findContractList 
	 * @Description : 取得大货合同数据
	 * @throws  	: Exception
	 * @return      : List<ContractEntity>
	 * @author      : shaoyun.tan
	 * @date        : 2017年11月20日
	 */
	public List<ContractEntity> findContractListForFinance(ContractEntity contractEntity) throws Exception {
		return contractEntityMapper.findListForFinance(contractEntity);
	}
	
	/** 
	 * @Title       : findContractCustomList 
	 * @Description : 取得定制合同数据
	 * @throws  	: Exception
	 * @return      : List<ContractCustomEntity>
	 * @author      : shaoyun.tan
	 * @date        : 2017年11月20日
	 */
	public List<ContractCustomEntity> findContractCustomListForFinance(ContractCustomEntity contractCustomEntity) throws Exception {
		return contractCustomEntityMapper.findListForFinance(contractCustomEntity);
	}
	
	/** 
	 * @Title       : findCustomDataInsertFinance 
	 * @Description : 更新所有相关表的状态
	 * @throws 		: Exception
	 * @author      : shaoyun.tan
	 * @date        : 2017年11月20日
	 */
	public void findCustomDataInsertFinance() throws Exception{
		FinanceEntity financeEntity = new FinanceEntity();
		//日期格式化格式
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
		SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd");//当月日期
		//当前日期
        Date date = new Date();
        Date date2 = new Date();
		//当前日历
        Calendar calendar = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar.setTime(date); // 设置为当前时间
        calendar2.setTime(date2); // 设置为当前时间
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 7); // 设置为上个星期一
        date = calendar.getTime(); //上个星期一日期
        calendar2.set(Calendar.DAY_OF_MONTH, calendar2.get(Calendar.DAY_OF_MONTH) - 1); // 设置为上个星期日
        date2 = calendar2.getTime(); //上个星期日日期
        String sunday = dateFormat2.format(date2);// 日期
        int days = Integer.parseInt(sunday);// 日期数
        int indexSun = (int) Math.ceil(days/(float)7);// 获取当前日期为当月第几个星期日
		//定制合同Entity
		ContractCustomEntity contractCustomEntity = new ContractCustomEntity();
		//定制合同数据插入
		contractCustomEntity.setFinanceStatus("0");
		contractCustomEntity.setContractDeliveryDate(date);
		contractCustomEntity.setContractFinishDate(date2);
		List<ContractCustomEntity> contractCustomList = findContractCustomListForFinance(contractCustomEntity);
		if (contractCustomList != null && contractCustomList.size() > 0) {
			for (ContractCustomEntity cEntity : contractCustomList) {
				cEntity.preInsert();
				cEntity.setFinanceStatus("1");
				//contractCustomEntityMapper.updateStatus(cEntity);
				financeEntity.preInsert(); 
				//financeEntity.setFinanceContractId(cEntity.getContractId());
				financeEntity.setFactoryId(1);
				financeEntity.setOgnizationId(cEntity.getCustomerId());
				financeEntity.setFinancePeriod(date2);
				financeEntity.setFinanceDate(date2);
				financeEntity.setFinanceContractNo(cEntity.getContractNo()+"."+dateFormat.format(date2)+".0"+indexSun);
				financeEntity.setFinanceCategory(ResourcesUtil.getConfig("financeCategory06"));
				financeEntity.setFinanceItemId(1);
				//贷方金额
				financeEntity.setCreditAmount(cEntity.getContractCost());
				financeEntity.setFinanceCurrency(cEntity.getContractCurrencyCd());
				financeEntity.setOrderStatus(ResourcesUtil.getConfig("financeOrderStatus_00"));
				financeEntity.setAccountsStatus(ResourcesUtil.getConfig("financeStatus02"));
				financeEntity.setSettlementStatus(ResourcesUtil.getConfig("settlementStatus02"));
				financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
				financeEntityMapper.insert(financeEntity);
				financeEntity = new FinanceEntity();
			}
		}
	}
	
	/** 
	 * @Title       : findDataInsertFinance 
	 * @Description : 更新所有相关表的状态
	 * @throws 		: Exception
	 * @author      : shaoyun.tan
	 * @date        : 2017年11月20日
	 */
	public void findDataInsertFinance() throws Exception{
		FinanceEntity financeEntity = new FinanceEntity();
		//采购合同Entity
		ContractMeterialEntity contractMeterialEntity = new ContractMeterialEntity();
		//外发加工合同Entity
		ContractProcessingEntity contractProcessingEntity = new ContractProcessingEntity();
		//预付款Entity
		ContractAdvanceEntity contractAdvanceEntity = new ContractAdvanceEntity();
		//样品需求Entity
		SampleEntity sampleEntity = new SampleEntity();
		//大货合同Entity
		ContractEntity contractEntity = new ContractEntity();
		//采购合同数据插入
		contractMeterialEntity.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
		contractMeterialEntity.setFinanceStatus("0");
		List<ContractMeterialEntity> contractMeterialList = findContractMeterialListForFinance(contractMeterialEntity);
		if (contractMeterialList != null && contractMeterialList.size() > 0) {
			for (ContractMeterialEntity cEntity : contractMeterialList) {
				cEntity.preInsert();
				cEntity.setFinanceStatus("1");
				contractMeterialEntityMapper.updateStatus(cEntity);
				financeEntity.preInsert();
				financeEntity.setFinanceContractId(cEntity.getContractMeterialId());
				financeEntity.setFactoryId(1);
				financeEntity.setOgnizationId(cEntity.getContractPartyB());
				financeEntity.setFinancePeriod(new Date());
				financeEntity.setFinanceDate(new Date());
				financeEntity.setFinanceContractNo(cEntity.getContractMeterialNo());
				financeEntity.setFinanceCategory(ResourcesUtil.getConfig("financeCategory01"));
				financeEntity.setFinanceItemId(1);
				//借方金额
				financeEntity.setDebitAmount(cEntity.getContractAmount());
				financeEntity.setFinanceCurrency(ResourcesUtil.getConfig("quotationCurrencyCNY"));
				financeEntity.setOrderStatus(ResourcesUtil.getConfig("financeOrderStatus_00"));
				financeEntity.setAccountsStatus(ResourcesUtil.getConfig("financeStatus02"));
				financeEntity.setSettlementStatus(ResourcesUtil.getConfig("settlementStatus02"));
				financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
				financeEntityMapper.insert(financeEntity);
				financeEntity = new FinanceEntity();
			}
		}
		
		//外发加工合同数据插入
		contractProcessingEntity.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
		contractProcessingEntity.setFinanceStatus("0");
		List<ContractProcessingEntity> contractProcessingList = findContractProcessingListForFinance(contractProcessingEntity);
		if (contractProcessingList != null && contractProcessingList.size() > 0) {
			for (ContractProcessingEntity cEntity : contractProcessingList) {
				cEntity.preInsert();
				cEntity.setFinanceStatus("1");
				contractProcessingEntityMapper.updateStatus(cEntity);
				financeEntity.preInsert();
				financeEntity.setFinanceContractId(cEntity.getContractProcessId());
				financeEntity.setFactoryId(1);
				financeEntity.setOgnizationId(cEntity.getContractPartyB());
				financeEntity.setFinancePeriod(new Date());
				financeEntity.setFinanceDate(new Date());
				financeEntity.setFinanceContractNo(cEntity.getContractProcessNo());
				financeEntity.setFinanceCategory(ResourcesUtil.getConfig("financeCategory02"));
				financeEntity.setFinanceItemId(1);
				//借方金额
				financeEntity.setDebitAmount(cEntity.getContractAmount());
				financeEntity.setFinanceCurrency(ResourcesUtil.getConfig("quotationCurrencyCNY"));
				financeEntity.setOrderStatus(ResourcesUtil.getConfig("financeOrderStatus_00"));
				financeEntity.setAccountsStatus(ResourcesUtil.getConfig("financeStatus02"));
				financeEntity.setSettlementStatus(ResourcesUtil.getConfig("settlementStatus02"));
				financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
				financeEntityMapper.insert(financeEntity);
				financeEntity = new FinanceEntity();
			}
		}
		//预付款数据插入
		contractAdvanceEntity.setStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
		contractAdvanceEntity.setFinanceStatus("0");
		List<ContractAdvanceEntity> contractAdvanceList = findContractAdvanceListForFinance(contractAdvanceEntity);
		if (contractAdvanceList != null && contractAdvanceList.size() > 0) {
			for (ContractAdvanceEntity cEntity : contractAdvanceList) {
				cEntity.preInsert();
				cEntity.setFinanceStatus("1");
				contractAdvanceEntityMapper.updateStatus(cEntity);
				financeEntity.preInsert();
				financeEntity.setFinanceContractId(cEntity.getAdvanceId());
				financeEntity.setFactoryId(1);
				financeEntity.setOgnizationId(cEntity.getOgnizationId());
				financeEntity.setFinancePeriod(new Date());
				financeEntity.setFinanceDate(new Date());
				financeEntity.setFinanceContractNo(cEntity.getAdvanceNo());
				financeEntity.setFinanceCategory(ResourcesUtil.getConfig("financeCategory03"));
				financeEntity.setFinanceItemId(1);
				//借方金额
				financeEntity.setDebitAmount(cEntity.getAdvanceAmount());
				financeEntity.setFinanceCurrency(ResourcesUtil.getConfig("quotationCurrencyCNY"));
				financeEntity.setOrderStatus(ResourcesUtil.getConfig("financeOrderStatus_00"));
				financeEntity.setAccountsStatus(ResourcesUtil.getConfig("financeStatus02"));
				financeEntity.setSettlementStatus(ResourcesUtil.getConfig("settlementStatus02"));
				financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
				financeEntityMapper.insert(financeEntity);
				financeEntity = new FinanceEntity();
			}
		}
		//样品数据插入
		sampleEntity.setSampleRequestStatus(ResourcesUtil.getConfig("specimen_production_status_done"));
		sampleEntity.setFinanceStatus("0");
		List<SampleEntity> sampleList = sampleEntityMapper.findListForFinance(sampleEntity);
		if (sampleList != null && sampleList.size() > 0) {
			for (SampleEntity cEntity : sampleList) {
				cEntity.preInsert();
				cEntity.setFinanceStatus("1");
				sampleEntityMapper.updateStatus(cEntity);
				financeEntity.preInsert();
				financeEntity.setFinanceContractId(cEntity.getSampleRequestId());
				financeEntity.setFactoryId(1);
				financeEntity.setOgnizationId(cEntity.getCustomerId());
				financeEntity.setFinancePeriod(new Date());
				financeEntity.setFinanceDate(new Date());
				financeEntity.setFinanceContractNo(cEntity.getSampleRequestNo());
				financeEntity.setFinanceCategory(ResourcesUtil.getConfig("financeCategory04"));
				financeEntity.setFinanceItemId(1);
				//贷方金额
				financeEntity.setCreditAmount(cEntity.getSampleRequestSizeCost());
				financeEntity.setFinanceCurrency(ResourcesUtil.getConfig("quotationCurrencyCNY"));
				financeEntity.setOrderStatus(ResourcesUtil.getConfig("financeOrderStatus_00"));
				financeEntity.setAccountsStatus(ResourcesUtil.getConfig("financeStatus02"));
				financeEntity.setSettlementStatus(ResourcesUtil.getConfig("settlementStatus02"));
				financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
				financeEntity.setRemarks(cEntity.getRemarks());
				financeEntityMapper.insert(financeEntity);
				financeEntity = new FinanceEntity();
			}
		}
		//大货合同数据插入
		contractEntity.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
		contractEntity.setFinanceStatus("0");
		List<ContractEntity> contractList = contractEntityMapper.findListForFinance(contractEntity);
		if (contractList != null && contractList.size() > 0) {
			for (ContractEntity cEntity : contractList) {
				cEntity.preInsert();
				cEntity.setFinanceStatus("1");
				contractEntityMapper.updateStatus(cEntity);
				financeEntity.preInsert();
				financeEntity.setFinanceContractId(cEntity.getContractId());
				financeEntity.setFactoryId(1);
				financeEntity.setOgnizationId(cEntity.getCustomerId());
				financeEntity.setFinancePeriod(new Date());
				financeEntity.setFinanceDate(new Date());
				financeEntity.setFinanceContractNo(cEntity.getContractNo());
				financeEntity.setFinanceCategory(ResourcesUtil.getConfig("financeCategory05"));
				financeEntity.setFinanceItemId(1);
				//贷方金额
				financeEntity.setCreditAmount(cEntity.getContractCost());
				financeEntity.setFinanceCurrency(cEntity.getContractCurrencyCd());
				financeEntity.setOrderStatus(ResourcesUtil.getConfig("financeOrderStatus_00"));
				financeEntity.setAccountsStatus(ResourcesUtil.getConfig("financeStatus02"));
				financeEntity.setSettlementStatus(ResourcesUtil.getConfig("settlementStatus02"));
				financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
				financeEntityMapper.insert(financeEntity);
				financeEntity = new FinanceEntity();
			}
		}
	}
	
	/**
	 * @Title : findDataInsertFinanceOgn
	 * @Description : 更新所有相关表的状态
	 * @throws Exception
	 * @author : shaoyun.tan
	 * @date : 2018年01月30日
	 */
	public void findDataInsertFinanceOgn() throws Exception{
		//日期格式化格式
		SimpleDateFormat dateFormatYMD = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat dateFormatYM = new SimpleDateFormat("yyyy-MM");
		//当前日期
        Date dateLast = new Date();
        Date dateThis = new Date();
        //当前日历
        Calendar calendarLast = Calendar.getInstance();
        Calendar calendarThis = Calendar.getInstance();
        calendarLast.setTime(dateLast); // 设置为当前时间
        calendarLast.set(Calendar.MONTH, calendarLast.get(Calendar.MONTH) - 2); // 设置为上个月
        calendarThis.setTime(dateLast); // 设置为当前时间
        calendarThis.set(Calendar.MONTH, calendarLast.get(Calendar.MONTH) - 1); // 设置为当前月
        //上个月日期
        dateLast = calendarLast.getTime();
        //当前月日期
        dateThis = calendarThis.getTime();
        //财务明细实体
        FinanceEntity thisMonthData = null;
        //财务结算实体
        OgnizationSettlementEntity settlementEntity = new OgnizationSettlementEntity();
        //初始数据
        OgnizationSettlementEntity settlementEntityInit = new OgnizationSettlementEntity();
        //上个月的财务结算数据
        OgnizationSettlementEntity lastMonthData = null;
        //财务结算集合
        List<OgnizationSettlementEntity> settlementList = new ArrayList<>();
        // 组织集
        List<Ognization> ognizationList = ognizationDao.findCuSuList(new Ognization());
        if (ognizationList != null && ognizationList.size() > 0) {
			for (Ognization ognization : ognizationList) {
				settlementEntityInit = initFinanceDao.getByOgnizationId(ognization.getId());
				if (settlementEntityInit != null) {
					lastMonthData = financeEntityMapper.getLastMonthSettleData(dateFormatYMD.format(dateLast),ognization.getId());
					if (lastMonthData == null) {
						lastMonthData = settlementEntityInit;
					}
					thisMonthData = financeEntityMapper.getThisMonthSettleData(dateFormatYMD.format(dateThis),ognization.getId(),ResourcesUtil.getConfig("settlementStatus02"));
					//组织Id
					settlementEntity.setOgnizationId(ognization.getId());
					//期间
					settlementEntity.setFinancePeriodStr(dateFormatYM.format(dateThis));
					//货币
					settlementEntity.setFinanceCurrency(lastMonthData.getFinanceCurrency());
					//期初借方余额
					settlementEntity.setInitialDebitAmount(nullReturn0(lastMonthData.getRealDebitAmount()));
					//期初贷方余额 
					settlementEntity.setInitialCreditAmount(nullReturn0(lastMonthData.getRealCreditAmount()));
					if (thisMonthData != null) {
						//本期借方金额
						settlementEntity.setPeriodDebitAmount(nullReturn0(thisMonthData.getDebitAmount()));
						//本期贷方金额
						settlementEntity.setPeriodCreditAmount(nullReturn0(thisMonthData.getCreditAmount()));
						//实际借方金额 = 期初借方余额  + 本期借方金额
						settlementEntity.setRealDebitAmount(nullReturn0(thisMonthData.getDebitAmount()).add(nullReturn0(lastMonthData.getRealDebitAmount())));
						//实际贷方金额 = 期初贷方余额  + 本期贷方金额
						settlementEntity.setRealCreditAmount(nullReturn0(thisMonthData.getCreditAmount()).add(nullReturn0(lastMonthData.getRealCreditAmount())));
						//设置为已结算
						thisMonthData.setSettlementStatus(ResourcesUtil.getConfig("settlementStatus01"));
						thisMonthData.setFinancePeriodStr(dateFormatYMD.format(dateThis));
						thisMonthData.preUpdate();
						//更新结算状态
						financeEntityMapper.updateSettlementStatus(thisMonthData);
						
					}else {
						//本期借方金额
						settlementEntity.setPeriodDebitAmount(new BigDecimal(0));
						//本期贷方金额
						settlementEntity.setPeriodCreditAmount(new BigDecimal(0));
						//实际借方金额 = 期初借方余额  + 本期借方金额
						settlementEntity.setRealDebitAmount(nullReturn0(lastMonthData.getRealDebitAmount()));
						//实际贷方金额 = 期初贷方余额  + 本期贷方金额
						settlementEntity.setRealCreditAmount(nullReturn0(lastMonthData.getRealCreditAmount()));
					}
					settlementEntity.preInsert();
					settlementList.add(settlementEntity);
					settlementEntity = new OgnizationSettlementEntity();
				}
			}
			if (settlementList != null && settlementList.size() > 0) {
				settlementEntity.setSettlementList(settlementList);
				//数据保存
				initFinanceDao.insertList(settlementEntity);
			}
		}
	}
	
	/**
	 * BigDecimal如果为null则返回0
	 * @return
	 */
	public BigDecimal nullReturn0(BigDecimal bigDecimal){
		if (bigDecimal == null) {
			return new BigDecimal(0);
		}
		return bigDecimal;
	}
}
